import { Image, View } from '@tarojs/components';
import { eventCenter, getCurrentInstance } from "@tarojs/runtime";
import Taro, { ShareAppMessageReturn, useShareAppMessage } from '@tarojs/taro';
import data, { globalHost } from '../util/data';
import { useEffect, useState } from "react";
import { ApiPath, WorkItem } from '../common/work-detail/msg';
import { sendGet } from '../../utils/http';
import "./index.less";

const host = globalHost

const Community = () => {
	const [imageList, setImageList] = useState<WorkItem[]>([]);

	useShareAppMessage(() => {
		return {
			title: '免费AI聊天和绘画,用它就够了',
			path: '/pages/community/index',
			imageUrl: data.shareImgUrl
		} as ShareAppMessageReturn
	})

	const onShow = () => {
		sendGet(host + ApiPath.LIST, '', {
			success: (res) => {
				let works = res.data.data as WorkItem[];
				if (works.length != imageList.length) {
					console.log('最新的广场作品：', works)
					// setImageList([]);
					setImageList(works);
				}
			}
		})
	}

	useEffect(() => {
		const onShowEventId = getCurrentInstance().router?.onShow
		eventCenter.on(onShowEventId ? onShowEventId : "空ID", onShow, this)
		Taro.setNavigationBarColor({ backgroundColor: '#2c2c31', frontColor: '#ffffff' })
		Taro.stopPullDownRefresh()
		// Taro.showShareMenu({
		// 	withShareTicket: true
		// })
	}, [])

	const handleImageClick = (workItem: WorkItem) => {
		Taro.navigateTo({
			url: `/pages/common/work-detail/index?workItem=${encodeURIComponent(JSON.stringify(workItem))}&imageType=${workItem.uIndex}`,
		})
	}

	return (
		<View className='column-wrapper'>
			{imageList.reverse().map((item) => (
				<View className='item' key={item.id} onClick={() => { handleImageClick(item) }}>
					<Image className="image" src={item.imageUrl} mode='widthFix' />
				</View>
			))}
		</View>
	)
}

export default Community;
